<template>
  <el-select
    filterable
    remote
    reserve-keyword
    default-first-option
    placeholder="请选择合作机构"
    :value="value"
    :remote-method="remoteMethod"
    :loading="loading"
    @change="handleChange"
  >
    <el-option
      v-for="item in options"
      :key="item.agency_id"
      :label="item.agency_name"
      :value="item.agency_id"
    ></el-option>
  </el-select>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  components: {},
  props: {
    value: {
      type: String,
      default: '',
    },
    agencyType: {
      type: Number,
      default: 6,
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  data() {
    return {
      loading: false,
      options: [],
    }
  },
  computed: {
    ...mapGetters(['accessCreditAgency', 'accessBankAgency', 'accessGovAgency']),
    currentAgency() {
      if (this.agencyType === 3) {
        return this.accessGovAgency
      } else if (this.agencyType === 1) {
        return this.accessBankAgency
      }
      return this.accessCreditAgency
    },
  },
  watch: {
    agencyType: {
      handler: function () {
        this.init()
      },
      immediate: true,
    },
  },
  created() {
    // this.init()
  },
  mounted() {},
  methods: {
    init() {
      this.getData().then(() => {
        this.remoteMethod()
      })
    },
    getData() {
      if (this.agencyType === 3) {
        return this.$store.dispatch('getAccessGovAgency')
      } else if (this.agencyType === 1) {
        return this.$store.dispatch('getAccessBankAgency')
      }
      return this.$store.dispatch('getAccessCreidtAgency')
    },
    async remoteMethod(query = '') {
      if (!query) {
        this.options = this.currentAgency
      } else {
        this.options = this.currentAgency.filter(it => it.agency_name.includes(query))
      }
    },
    handleChange(val) {
      const item = this.options.find(it => it.agency_id === val)
      this.$emit('change', val, item)
    },
  },
}
</script>

<style lang="scss" scoped></style>
